<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{total}} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/UploadExcel')">excel导入</el-button>
          <el-button type="danger" size="small" @click="Hexcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index"/>
          <el-table-column label="姓名" prop="username"/>
          <el-table-column label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" style="width:50px"> -->
              <ImageHolder :src="scope.row.staffPhoto"></ImageHolder>
            </template>
            </el-table-column>
          <el-table-column label="工号" prop="workNumber"/>
          <el-table-column label="聘用形式">
            <template v-slot="scope">
             {{formatType(scope.row.formOfEmployment)}}
            </template>
            </el-table-column>
          <el-table-column label="部门" prop="departmentName"/>
          <el-table-column label="入职时间" prop="timeOfEntry" sortable/>
          <el-table-column label="账户状态"/>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
      @size-change="hSizeChange"
      @current-change="hCurrentChange"
      :current-page.sync="page"
      :page-sizes="[3, 5, 10, 20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
            </el-pagination>
        </el-row>
      </el-card>
    </div>
    <!-- 弹框盒子 -->
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <empDialog @close="showDialog=false" @success="hSuccess" v-if="showDialog"></empDialog>
    </el-dialog>
    <!-- 角色分配弹框 -->
    <el-dialog :visible.sync="showDialogRole" title="权限分配">
  <AssignRole @delsuccess="delsuccess" :employeeId="curId" v-if="showDialogRole" @success="hSuccessRole"/>
</el-dialog>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import EmployeeEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import {getEmployees,delEmployee} from '@/api/employees'
export default {
  components:{
    empDialog, AssignRole
  },
  data() {
    return {
      size:3, //每页几条数据
      page:1, //当前显示第几页
      total:0, //总条数
      // 表格信息
      list:[],
      // 弹框显示与隐藏
      showDialog: false,
      showDialogRole: false,
      curId:''
    };
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 权限弹框点击取消
    delsuccess(){
 this.showDialogRole=false
    },
    // 权限分配成功关闭弹框
    hSuccessRole(){
      this.showDialogRole=false
    },
    // 角色分配弹框
    hAssignRole(id){
    this.showDialogRole= true
    this.curId = id
    },
     // 用户点击的页码
    hCurrentChange(curPage){
      // 更新页码
 this.page = curPage
//  重发请求
this.loadEmployees()
    },
    // 每页几条
    hSizeChange(curSize){
      // 更新每页的条数
this.size = curSize
//  重发请求
this.loadEmployees()
    },
    async loadEmployees(){
    const res = await getEmployees(this.page,this.size)
    console.log('员工信息列表',res);
    this.list = res.data.rows
    this.total = res.data.total
    },
    // 枚举
    formatType(typeId){
      const item = EmployeeEnum.hireType.find(item => item.id === typeId)
      if(item){
        return item.value 
      }else{
        return '未知'
      }
    },
    // 删除发送请求
      async doDel(id) {
      try {
        const res = await delEmployee(id);
        console.log(res);
        // 1. 提示
        this.$message.success("删除成功");
        // 2. 重新请求
        this.loadEmployees()
      } catch (err) {
        console.log(err);
        this.$message.error("删除失败");
      }
    },
     // 删除
    hDel(id) {
      this.$confirm("你确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.doDel(id);
          // 如果删除页面最后一条数据,页码要减一
          if (this.list.length === 1) {
            this.pageParams.page--;
            if (this.pageParams.page === 0) {
              this.page = 1;
            }
          }
          this.loadEmployees()
        })
        .catch(() => {
        });
    },
    // 员工添加成功，关闭弹层
    hSuccess(){
      this.showDialog = false
       // 添加成功，进入最后一页看数据
    this.total++
      // 最后一页
    this.page = Math.ceil(this.total / this.size)
      this.loadEmployees()
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = EmployeeEnum[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    // 导出excel
    Hexcel(){
       import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployees(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
  })
})
    }
  },
}
</script>